﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Srvtools;

public partial class WorkTimeN_ViewEmpWorkOn : System.Web.UI.Page
{
    private Hashtable EmpWorkOnDateTable;
    private Hashtable CompWorkDateDefine;
    private Hashtable EmpOverTimeDateTable;
    private DataTable EmpAddUp;
    private DataTable SpecialWorkTime;

    private bool IsDayWork = false;
    private string StartWorkOn;
    private string EndWorkOn;
    private string LateOfStartTime;
    private string LeaveOfEndTime;

    private DateTime FirstDayOfThisMonth;
    private DateTime LastDayOfThisMonth;
    string EmpId = "";

    protected void Page_Load(object sender, EventArgs e)
    {

        string TheYear = "";
        string TheMonth = "";
        string sEmpId = "";
        string sSelf = "";

        //输入变量的定义 EId=1(是否可选择人员是=0,144(工号),2008(年),2(月)
        if (this.Request.QueryString["ItemParam"].IndexOf("EId") != -1)
        {
            String Inv = this.Request.QueryString["ItemParam"].ToString().Replace("EId=", "");
            string[] Temp = Inv.Split(new char[1] { ',' });

            if (Temp[0] == "1")
            {
                sSelf = Temp[0];
                sEmpId = int.Parse(Temp[1]).ToString();
                if (sEmpId == "0") sEmpId = "";
                TheYear = Temp[2];
                if (TheYear == "0") TheYear = "";
                TheMonth = Temp[3];
                if (TheMonth == "0") TheMonth = "";
            }
            else
            {
                sEmpId = Srvtools.CliUtils.GetValue("_UserCode")[1].ToString();
                sEmpId = int.Parse(sEmpId).ToString();
                sSelf = "0";
            }
        }
        else
        {
            return;
        }

        //
        if (!IsPostBack)
        {
            if (sEmpId.Length > 0)
            {
                SelUser.ReadOnly(sEmpId, Srvtools.CliUtils.fUserName);
                //WebRefVal1.BindingValue = sEmpId;
                //EmpId = sEmpId;

            }
            else
            {
                sEmpId = Srvtools.CliUtils.GetValue("_UserCode")[1].ToString();
                EmpId = int.Parse(sEmpId).ToString();
                //WebRefVal1.BindingValue = EmpId;
                SelUser.SelUserInti(sEmpId, Srvtools.CliUtils.fUserName);

            }

            if (TheYear.Length > 0 && TheMonth.Length > 0)
            {
                DateTime Std = new DateTime(int.Parse(TheYear), int.Parse(TheMonth), 1);
                Calendar1.VisibleDate = Std;
            }

            Calendar1.DataBind();

            MasterPage_MasterPage mpg = (MasterPage_MasterPage)this.Page.Master;
            mpg.HelpHref = "~/Help/WorkTime/查阅本人考勤.htm";
            mpg.PageName = "查看员工的月考勤";
            mpg.PicUrl = "";
            mpg.IntiBar();
        }
        else
        {
            string ss = SelUser.EmployeeId.ToString();
            if (ss.Length > 0) EmpId = ss;
        }
    }

    //GetWorkTime_AddUpList
    protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {

        if ((FirstDayOfThisMonth <= e.Day.Date) && (LastDayOfThisMonth >= e.Day.Date))
        {
            e.Cell.VerticalAlign = VerticalAlign.Top;
            string DKey = e.Day.Date.Year.ToString().Trim() + "-" + e.Day.Date.Month.ToString().Trim() + "-" + e.Day.Date.Day.ToString().Trim();
            bool NowIsWorkingDay = IsWorkingDay(e.Day.Date);
            string ShowText = "<span style=' text-align:left'><br/><br/>";

            //考勤汇总数据
            DataRow[] drs = EmpAddUp.Select("Wyear=" + e.Day.Date.Year + " and Wmonth=" + e.Day.Date.Month + " and Wday=" + e.Day.Date.Day);
            double daynum = 0;
            foreach (DataRow dr in drs)
            {
                ShowText += " + " + dr["LeaveTypeName"].ToString() + " " + dr["WaddHour"].ToString() + " 小时<br/>";
                daynum += Convert.ToDouble(dr["WaddHour"].ToString());
            }


            e.Cell.BorderColor = System.Drawing.Color.Black;
            e.Cell.BorderWidth = 1;
            e.Cell.BorderStyle = BorderStyle.Solid;

            //考勤小时
            double dwh = 0;
            string checkintime = "";

            //是否工作日
            if (IsDayWork)
            {
                dwh = DayWorkHours((DateTime[])EmpWorkOnDateTable[DKey], out checkintime);

            }
            else
            {
                dwh = SpecialWorkHours((DateTime[])EmpWorkOnDateTable[DKey], (DateTime[])EmpWorkOnDateTable[Convert.ToDateTime(DKey).AddDays(1).ToString("yyyy-M-d")], out checkintime);
            }
            if (dwh > 0)
            {
                daynum += dwh;
                if (daynum == 8)
                {
                    ShowText += " 有正常考勤<br/>";
                }
                else
                {
                    ShowText += " + 有考勤" + dwh + " 小时<br/>";
                }
            }
            else if (dwh == -1)
            {
                if (daynum == 0)
                {
                    daynum = -1;
                }

            }

            if (daynum >= 7.8)
            {
                e.Cell.BackColor = System.Drawing.Color.LightGray;
            }
            else
            {
                if (NowIsWorkingDay) //非工作日
                {
                    if (daynum == 0)
                    {
                        e.Cell.BackColor = System.Drawing.Color.Yellow;
                        ShowText += " 无考勤记录 <br/>";
                    }
                    else if (daynum == -1)
                    {
                        e.Cell.BackColor = System.Drawing.Color.GreenYellow;
                        ShowText += " 只有一次考勤<br/>";
                    }
                    else
                    {
                        e.Cell.BackColor = System.Drawing.Color.GreenYellow;
                        ShowText += " + 缺工作时间 <span style='color:red'>" + (8 - daynum).ToString() + "</span> 小时<br/>";
                    }
                }
            }

            ShowText += checkintime;

            if (NowIsWorkingDay == false) //非工作日
            {
                e.Cell.BackColor = System.Drawing.Color.Tomato;
            }

            e.Cell.Controls.Add(new LiteralControl(ShowText + "</span>"));
        }
    }

    private double DayWorkHours(DateTime[] DtIn, out string checkintime)
    {
        if (DtIn == null)
        {
            checkintime = "";
            return 0;
        }
        else
        {
            DateTime cutWs = Convert.ToDateTime(DtIn[0].ToString("yyyy-MM-dd") + " " + LateOfStartTime + ":00");
            DateTime cutWe = Convert.ToDateTime(DtIn[0].ToString("yyyy-MM-dd") + " " + EndWorkOn + ":00");

            return WorkHours(DtIn, cutWs, cutWe, out checkintime);
        }
        //return LackHours =0= 8 ? 8 : LackHours;
        //return Convert.ToInt32(Math.Ceiling(eet.Subtract(sst).TotalHours)) >= 8;
    }

    private double SpecialWorkHours(DateTime[] DtInToday, DateTime[] DtInTomorrow, out string checkintime)
    {
        checkintime = "";

        //考勤相差小于10 正确考勤记录
        DateTime[] dts = new DateTime[2];
        if (DtInToday == null)
        {
            return 0;
        }
        DateTime sst = DtInToday[0];
        DateTime eet = DtInToday[1];
        double ct = eet.Subtract(sst).TotalHours;
        if (ct <= 10 && ct != 0)
        {
            dts[0] = sst;
            dts[1] = eet;
        }
        else
        {
            if (DtInTomorrow == null)
            {
                return 0;
            }
            sst = DtInToday[1];
            eet = DtInTomorrow[0];
            ct = eet.Subtract(sst).TotalHours;
            if (ct <= 10 && ct != 0)
            {
                dts[0] = sst;
                dts[1] = eet;
            }
        }

        //套上班时间
        foreach (DataRow dr in SpecialWorkTime.Rows)
        {
            DateTime st = new DateTime();
            DateTime et = new DateTime();

            //套上班时间相同
            st = Convert.ToDateTime(dts[0].ToString("yyyy-MM-dd") + " " + dr["st"] + ":00");
            et = Convert.ToDateTime(dts[0].ToString("yyyy-MM-dd") + " " + dr["sct"] + ":00");
            if (dts[0].CompareTo(st) >= 0 & dts[0].CompareTo(et) <= 0)
            {
                return WorkHours(dts, Convert.ToDateTime(dts[0].ToString("yyyy-MM-dd") + " " + dr["sct"] + ":00"),
                    Convert.ToDateTime(dts[1].ToString("yyyy-MM-dd") + " " + dr["et"].ToString() + ":00"), out checkintime);
            }

            //套下班时间相同
            st = Convert.ToDateTime(dts[1].ToString("yyyy-MM-dd") + " " + dr["ect"] + ":00");
            et = Convert.ToDateTime(dts[1].ToString("yyyy-MM-dd") + " " + dr["et"] + ":00");
            if (dts[1].CompareTo(st) >= 0 & dts[1].CompareTo(et) <= 0)
            {
                return WorkHours(dts, Convert.ToDateTime(dts[0].ToString("yyyy-MM-dd") + " " + dr["sct"] + ":00"),
                    Convert.ToDateTime(dts[1].ToString("yyyy-MM-dd") + " " + dr["et"].ToString() + ":00"), out checkintime);
            }
        }
        if (DtInToday[0] != null)
        {
            return -1;
        }
        else
        {
            return 0;
        }
    }

    /// <summary>
    /// 获取考勤时间
    /// </summary>
    /// <param name="DtIn">考勤时间 早晚</param>
    /// <param name="cutWs">考勤规定最晚上班时间</param>
    /// <param name="cutWe">考勤规定最早下班时间</param>
    /// <returns></returns>
    private double WorkHours(DateTime[] DtIn, DateTime cutWs, DateTime cutWe, out string checkintime)
    {


        DateTime sst = DtIn[0];
        DateTime eet = DtIn[1];

        double LackHours = 0;
        LackHours += sst.Subtract(cutWs).TotalHours >= 0 ? sst.Subtract(cutWs).TotalHours : 0;
        LackHours += eet.Subtract(cutWe).TotalHours >= 0 ? 0 : cutWe.Subtract(eet).TotalHours;

        checkintime = "<br/><span style='color:blue'>" + sst + " 至 " + eet + "</span>";
        if (LackHours == 0)
        {
            return 8;
        }
        else
        {
            return Math.Round(8 - LackHours, 1);
        }
    }

    /// <summary>
    /// 取得本月某员工的的考勤和公司日期定义日的集合
    /// </summary>
    /// <param name="EmpId">员工工号</param>
    /// <param name="DateS">本月起始日</param>
    /// <param name="DataE">本月终止日</param>
    private void GetData(string EmpId, string DateS, string DataE)
    {
        //GetWorkOnType
        object[] myRet4 = CliUtils.CallMethod("SWorkTime", "GetWorkOnType", new object[] { "WorkTime_WorkOnTypeGroup.EmployeeId=" + EmpId });
        if (myRet4 != null)
        {
            if (myRet4[1].ToString() == "N")
            {
                if (((DataSet)myRet4[2]).Tables[0] != null && ((DataSet)myRet4[2]).Tables[0].Rows.Count > 0)
                {
                    DataRow dr = ((DataSet)myRet4[2]).Tables[0].Rows[0];

                    StartWorkOn = dr["st"].ToString();
                    EndWorkOn = dr["et"].ToString();
                    LateOfStartTime = dr["sct"].ToString();
                    LeaveOfEndTime = dr["ect"].ToString();
                }
                IsDayWork = true;
            }
            else
            {
                IsDayWork = false;
                SpecialWorkTime = ((DataSet)myRet4[2]).Tables[0];
            }
        }

        //本月考勤记录
        object[] objParam = new object[3];
        objParam[0] = EmpId;
        objParam[1] = Convert.ToDateTime(DateS).ToString("yyyy-MM-dd 00:00:00");
        objParam[2] = Convert.ToDateTime(DataE).AddDays(1).ToString("yyyy-MM-dd");
        object[] myRet = CliUtils.CallMethod("SWorkTime", "GetEmpWorkOnDateTable", objParam);
        if (myRet != null && (int)myRet[0] == 0)
        {
            EmpWorkOnDateTable = (Hashtable)myRet[1];
        }

        //本月节假日
        object[] objParam2 = new object[2];
        objParam2[0] = Convert.ToDateTime(DateS).ToString("yyyy-MM-dd 00:00:00");
        objParam2[1] = Convert.ToDateTime(DataE).ToString("yyyy-MM-dd 23:59:59");
        object[] myRet2 = CliUtils.CallMethod("SWorkTime", "GetCompWorkDateDefine", objParam2);
        if (myRet2 != null && (int)myRet2[0] == 0)
        {
            CompWorkDateDefine = (Hashtable)myRet2[1];
        }

        //本月考勤汇总
        object[] objParam3 = new object[1];
        string st = Convert.ToDateTime(DateS).ToString("yyyy-MM-dd 00:00:00");
        string et = Convert.ToDateTime(DataE).ToString("yyyy-MM-dd 23:59:59");
        objParam3[0] = " 1=1 and WorkTime_AddUp.EmployeeId = " + EmpId + " and cast(cast(Wyear as varchar(4))+'-'+cast(Wmonth as varchar(2))+'-'+cast(Wday as varchar(2))as datetime) >='" +
            st + "' and cast(cast(Wyear as varchar(4))+'-'+cast(Wmonth as varchar(2))+'-'+cast(Wday as varchar(2))as datetime) <='" + et + "'";

        object[] myRet3 = CliUtils.CallMethod("SWorkTime", "GetWorkTime_AddUpList", objParam3);
        if (myRet3 != null && myRet3[1] != null)
        {
            EmpAddUp = ((DataSet)myRet3[1]).Tables[0];
        }
    }



    /// <summary>
    /// 判断是否为工作日
    /// </summary>
    /// <param name="Inday"></param>
    /// <returns></returns>
    private bool IsWorkingDay(DateTime Inday)
    {
        string DKey = Inday.Year.ToString().Trim() + "-" + Inday.Month.ToString().Trim() + "-" + Inday.Day.ToString().Trim();
        if (Inday.DayOfWeek == DayOfWeek.Saturday || Inday.DayOfWeek == DayOfWeek.Sunday)
        {
            if (CompWorkDateDefine.ContainsKey(DKey) == false)
            {
                return false;
            }
            else
            {
                object[] DtIn = (object[])CompWorkDateDefine[DKey];// { DTyp, DatePrepty };
                bool Dbk = (bool)DtIn[0];
                return Dbk;
            }
        }
        else
        {
            if (CompWorkDateDefine.ContainsKey(DKey) == false)
            {
                return true;
            }
            else
            {
                object[] DtIn = (object[])CompWorkDateDefine[DKey];// { DTyp, DatePrepty };
                bool Dbk = (bool)DtIn[0];
                return Dbk;
            }
        }

    }

    protected void Calendar1_PreRender(object sender, EventArgs e)
    {

        string ss2 = SelUser.EmployeeId;
        if (ss2.Length > 0) EmpId = ss2;

        string ss = SelUser.EmpName;
        if (ss.Length == 0)
        {
            ss = Srvtools.CliUtils.GetValue("_UserName")[1].ToString();
        }
        Calendar1.Caption = string.Format("<h2>{0}的考勤</h2>", ss);

        DateTime Std = new DateTime(1900, 1, 1, 1, 1, 1);
        if (Calendar1.VisibleDate < Std)
        {
            Std = DateTime.Now;
        }
        else
        {
            Std = Calendar1.VisibleDate;
        }

        int year = Std.Year;
        int month = Std.Month;
        FirstDayOfThisMonth = new DateTime(year, month, 1);
        LastDayOfThisMonth = new DateTime(year, month, DateTime.DaysInMonth(year, month));

        string DateS = FirstDayOfThisMonth.Year.ToString().Trim() + "-" + FirstDayOfThisMonth.Month.ToString().Trim() + "-" + FirstDayOfThisMonth.Day.ToString().Trim();
        string DataE = LastDayOfThisMonth.Year.ToString().Trim() + "-" + LastDayOfThisMonth.Month.ToString().Trim() + "-" + LastDayOfThisMonth.Day.ToString().Trim();


        GetData(EmpId, DateS, DataE);
    }

    protected void QueryEmpData_Click(object sender, EventArgs e)
    {
        EmpId = SelUser.EmployeeId;

        Calendar1.DataBind();
        //Load();
    }

}
